import * as vscode from 'vscode';
import { spawn, ChildProcess } from 'child_process';
import { logger } from '../logger';

// 定义日志级别枚举
export enum LogLevel {
    DEBUG = 'Debug',
    INFO = 'Info',
    WARN = 'Warn',
    ERROR = 'Error',
    FATAL = 'Fatal'
}

export class HiLogService {
    private static instance: HiLogService;
    private logProcess: ChildProcess | null = null;
    private deviceCheckInterval: NodeJS.Timeout | null = null;
    private onLogUpdateCallbacks: ((log: string) => void)[] = [];
    private deviceConnected: boolean = false;
    private isRunning: boolean = false;
    private logBuffer: string[] = [];
    private maxBufferSize: number = 1000; // 保留最近1000行日志
    private currentLogLevel: LogLevel = LogLevel.INFO; // 默认日志级别为 INFO

    private constructor() {
        // Private constructor to enforce singleton pattern
    }

    public static getInstance(): HiLogService {
        if (!HiLogService.instance) {
            HiLogService.instance = new HiLogService();
        }
        return HiLogService.instance;
    }

    // 设置日志级别
    public setLogLevel(level: LogLevel): void {
        if (this.currentLogLevel === level) {
            return; // 如果级别相同则不做任何改变
        }
        
        this.currentLogLevel = level;
        logger.info(`HiLog level changed to: ${level}`);
        
        // 如果当前正在运行日志流，则重启以应用新的日志级别
        if (this.isRunning && this.deviceConnected) {
            this.stopLogStream();
            this.startLogStream();
        }
    }

    // 获取当前日志级别
    public getLogLevel(): LogLevel {
        return this.currentLogLevel;
    }

    // 注册日志更新回调
    public onLogUpdate(callback: (log: string) => void): vscode.Disposable {
        this.onLogUpdateCallbacks.push(callback);
        // 如果已经有日志，立即调用回调发送缓存的日志
        if (this.logBuffer.length > 0) {
            callback(this.logBuffer.join('\n'));
        }

        return {
            dispose: () => {
                const index = this.onLogUpdateCallbacks.indexOf(callback);
                if (index !== -1) {
                    this.onLogUpdateCallbacks.splice(index, 1);
                }
            }
        };
    }

    // 检查设备是否连接
    public async checkDeviceConnection(): Promise<boolean> {
        return new Promise((resolve) => {
            const process = spawn('hdc', ['list']);
            let output = '';

            process.stdout.on('data', (data) => {
                output += data.toString();
            });

            process.on('close', (code) => {
                // 如果命令执行成功，并且输出中包含设备ID，则认为设备已连接
                const connected = code === 0 && /\S+-\S+/.test(output);
                resolve(connected);
            });

            process.on('error', () => {
                resolve(false);
            });
        });
    }

    // 开始监控设备连接状态
    public startDeviceMonitoring(): void {
        if (this.deviceCheckInterval) {
            clearInterval(this.deviceCheckInterval);
        }

        // 立即检查一次设备连接状态
        this.checkDeviceConnection().then(connected => {
            if (connected && !this.deviceConnected) {
                this.deviceConnected = true;
                this.startLogStream();
                vscode.window.showInformationMessage('设备已连接，HiLog 日志流已启动');
            } else if (!connected && this.deviceConnected) {
                this.deviceConnected = false;
                this.stopLogStream();
                vscode.window.showInformationMessage('设备已断开连接，HiLog 日志流已停止');
            }
        });

        // 每2秒检查一次设备连接状态
        this.deviceCheckInterval = setInterval(async () => {
            const connected = await this.checkDeviceConnection();
            
            if (connected && !this.deviceConnected) {
                this.deviceConnected = true;
                this.startLogStream();
                vscode.window.showInformationMessage('设备已连接，HiLog 日志流已启动');
            } else if (!connected && this.deviceConnected) {
                this.deviceConnected = false;
                this.stopLogStream();
                vscode.window.showInformationMessage('设备已断开连接，HiLog 日志流已停止');
            }
        }, 2000);
    }

    // 停止监控设备连接状态
    public stopDeviceMonitoring(): void {
        if (this.deviceCheckInterval) {
            clearInterval(this.deviceCheckInterval);
            this.deviceCheckInterval = null;
        }
        this.stopLogStream();
    }

    // 开始日志流
    private startLogStream(): void {
        if (this.isRunning) {
            return;
        }

        this.isRunning = true;
        logger.info(`Starting HiLog stream with level: ${this.currentLogLevel}...`);

        try {
            // 根据日志级别构建命令
            const args = ['shell', 'hilog'];
            
            // 如果是Debug级别，则添加Debug参数
            if (this.currentLogLevel === LogLevel.DEBUG) {
                args.push(LogLevel.DEBUG);
            }
            
            this.logProcess = spawn('hdc', args);

            this.logProcess.stdout?.on('data', (data) => {
                const logs = data.toString();
                this.addToLogBuffer(logs);
                
                // 通知所有订阅者
                this.onLogUpdateCallbacks.forEach(callback => {
                    callback(logs);
                });
            });

            this.logProcess.stderr?.on('data', (data) => {
                logger.error(`HiLog stderr: ${data.toString()}`);
            });

            this.logProcess.on('close', (code) => {
                logger.info(`HiLog process exited with code ${code}`);
                this.isRunning = false;
                this.logProcess = null;
            });

            this.logProcess.on('error', (err) => {
                logger.error(`Failed to start HiLog process: ${err.message}`);
                this.isRunning = false;
                this.logProcess = null;
            });
        } catch (error) {
            logger.error(`Error starting HiLog process: ${error instanceof Error ? error.message : 'Unknown error'}`);
            this.isRunning = false;
        }
    }

    // 停止日志流
    private stopLogStream(): void {
        if (this.logProcess) {
            this.logProcess.kill();
            this.logProcess = null;
        }
        this.isRunning = false;
        logger.info('HiLog stream stopped');
    }

    // 添加日志到缓冲区
    private addToLogBuffer(logs: string): void {
        const logLines = logs.split('\n').filter(line => line.trim());
        
        // 添加新日志行到缓冲区
        this.logBuffer = [...this.logBuffer, ...logLines];
        
        // 如果超出最大缓冲区大小，则移除最旧的日志
        if (this.logBuffer.length > this.maxBufferSize) {
            this.logBuffer = this.logBuffer.slice(this.logBuffer.length - this.maxBufferSize);
        }
    }

    // 清除日志缓冲区
    public clearLogBuffer(): void {
        this.logBuffer = [];
    }

    // 获取当前的日志缓冲区
    public getLogBuffer(): string[] {
        return [...this.logBuffer];
    }
}
